#include "qmlcpp.h"
#include <QDebug>

//add by myself
//#include <qtimer.h>
//#include <qapplication.h>
//#include <qmessagebox.h>
//#include <qstringlist.h>
#include <unistd.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <sys/ioctl.h>
#include <stdio.h>


//qmlCpp::qmlCpp()
qmlCpp::qmlCpp(QObject *parent) : QObject(parent)
{
#ifdef IMX6Q
   led_fb=open("/dev/leds_ctl",0);

   if(led_fb<0)
   {
       perror("open device led failed!");
       exit(1);
   }

   //RS232 tty
   fd = tf_modbus_open();
   qDebug()<<"tf_modbus construct function"<<endl;

   if (fd < 0) {
       //QMessageBox::warning(this, tr("Error"), tr("Fail to open serial port!"));
       return ;
    }

   m_notifier = new QSocketNotifier(fd, QSocketNotifier::Read, this);
   connect (m_notifier, SIGNAL(activated(int)), this, SLOT(remoteDataIncoming()));
#endif
}

void qmlCpp::remoteDataIncoming()
{
        char c;
        if (read(fd, &c, sizeof c) != 1) {
               // QMessageBox::warning(this, tr("Error"), tr("Receive error!"));
            qDebug()<<"read err"<<endl;
            return;
        }
        recvArr += c;

      //  qDebug()<<QString::number(c,16).toUpper()<<" ";
}

qmlCpp::~qmlCpp()
{

}

void qmlCpp::setLed(bool status)
{
     qDebug()<<"LED"<<status<<endl;

#ifdef IMX6Q
     if(status)
     {
         ioctl(led_fb,1,0);
     }
     else
     {
         ioctl(led_fb,0,0);
     }
#endif
}

QString qmlCpp::get_temp()
{
    int ret;
    float board_temp=0.0;
    QString str;

   ret = sendReadFloatReg(&board_temp, 53);
   if(ret<0) //Fail
   {
       qDebug()<<"read nothing"<<endl;
       str = "none";
   }
   else //success
   {
       str = QString::number(board_temp ,'f', 2);
       str += " C";
   }

    return str;
}
